package com.bd.demo.ui.page

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.bd.demo.R
import com.bd.demo.model.AppViewModel
import com.bd.demo.model.BleViewModel
import com.bd.demo.ui.theme.lightBackground
import com.bd.demo.ui.theme.text12NormalHint
import com.bd.demo.ui.theme.text14MediumBody
import com.bd.demo.ui.theme.text16BoldTitle
import com.bd.demo.ui.view.TitleBar
import com.clj.fastble.BleManager
import com.clj.fastble.data.BleDevice
import com.google.accompanist.insets.navigationBarsPadding
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

const val BLE_LIST_SCREEN = "ble_list_screen"

@Composable
fun BleListScreen(
    navController: NavHostController,
    app: AppViewModel,
    model: BleViewModel
) {
    // 是否显示刷新
    val isRefreshing by model.isRefreshing.observeAsState(initial = false)
    // 设备列表
    val devices by model.ble.scanDeviceListLive.observeAsState(listOf())

    // 协程
    val scope = rememberCoroutineScope()

    // 启动时刷新一次
    LaunchedEffect(Unit) {
        scope.launch {
            model.refreshBleDevices()
        }
        // 断开所有连接蓝牙设备
        BleManager.getInstance().disconnectAllDevice()
    }

    // UI
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(lightBackground)
            .navigationBarsPadding()
    ) {
        // 标题栏
        TitleBar(
            value = "蓝牙设备"
        )
        // 提示
        Text(
            text = "蓝牙扫描必须条件如下：\n1、打开手机蓝牙；\n2、打开位置信息开关；\n3、授权定位权限；\n每次下拉刷新会先检查一次，如果您已经拒绝过，请到手机设置中手动打开。",
            style = text14MediumBody,
            modifier = Modifier.padding(16.dp, 8.dp)
        )
        // 数据列表
        SwipeRefresh(
            state = rememberSwipeRefreshState(isRefreshing = isRefreshing),
            onRefresh = {
                scope.launch {
                    model.refreshBleDevices()
                }
            },
            modifier = Modifier
                .fillMaxSize()
                .weight(1f)
        ) {
            LazyColumn(
                modifier = Modifier
                    .fillMaxWidth()
                    .defaultMinSize(minHeight = 300.dp)
            ) {
                itemsIndexed(devices) { _, info ->
                    if (!info.name.isNullOrEmpty()) {
                        BleItem(
                            device = info,
                            onClick = {
                                // 开始连接
                                app.startLoading()
                                scope.launch {
                                    model.connectBleDevice(
                                        info,
                                        fail = { str ->
                                            app.cancelLoading()
                                            app.showSnackBar(str)
                                        },
                                        success = {
                                            app.cancelLoading()
                                            scope.launch(Dispatchers.Main) {
                                                navController.navigate(MESSAGE_SCREEN)
                                            }
                                        }
                                    )
                                }
                            }
                        )
                    }
                }
            }
        }
    }
}

@Composable
fun BleItem(
    device: BleDevice,
    onClick: () -> Unit = {}
) {
    Column {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(55.dp)
                .clickable {
                    // 点击蓝牙设备
                    onClick.invoke()
                }
                .padding(16.dp, 0.dp, 16.dp, 0.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Icon(
                painter = painterResource(id = R.drawable.ic_baseline_bluetooth_audio_24),
                contentDescription = "图标"
            )
            Column {
                Text(text = device.name?: "", style = text16BoldTitle)
                Text(text = device.mac, style = text12NormalHint)
            }
        }
        Divider()
    }
}